package com.edu.scnu.show;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MenuPanel extends JPanel {
    private Image backgroundImage;
    private Thread thread;
    private JPanel jPanel;
   
    public void setBackgroundImage(Image backgroundImage) {
		this.backgroundImage = backgroundImage;
	}

	public void setThread(Thread thread) {
		this.thread = thread;
	}

	public void setjPanel(JPanel jPanel) {
		this.jPanel = jPanel;
	}

	public MenuPanel(CardLayout cardLayout, JPanel mainPanel) {
        // 加载背景图片
        backgroundImage = new ImageIcon("image/background/8.png").getImage();

        // 设置布局为 GridBagLayout
        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(10, 10, 10, 10);

        // 创建并添加开始游戏按钮
        JButton startButton = createStyledButton("开始游戏");
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(mainPanel, "Game");
                // Request focus for game panel after switching
                mainPanel.getComponent(1).requestFocusInWindow();
                if(thread != null) {
	    			thread.start(); // 启动线程
	    		}
	    		// 如果jpanel是runnable的子类实体对象
	    		if(jPanel instanceof Runnable) {
	    			// 已经做了类型判定，强制类型转换不会出错
	    			new Thread((Runnable)jPanel).start();
	    		}
            }
        });
        gbc.gridy = 0; // 设置按钮位置
        this.add(startButton, gbc);

        // 创建并添加自定义样式的退出按钮
        JButton exitButton = createStyledButton("退出游戏");
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0); // 退出程序
            }
        });

        gbc.gridy = 1; // 设置按钮位置
        this.add(exitButton, gbc);
    }
	
	private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 20));
        button.setForeground(Color.GREEN);
        button.setBackground(new Color(0, 123, 255));
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
        button.setContentAreaFilled(false); // 去掉默认内容区域
        button.setOpaque(true); // 设置背景色不透明
        button.setPreferredSize(new Dimension(110, 50));
        
        return button;
    }

	
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 绘制背景图片
        if (backgroundImage != null) {
            g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
        }
    }
}
